package com.ndood.admin.core.web.async;

import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

@RestController
public class AsyncController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private MockQueue mockQueue;

	@Autowired 
	private DeferredResultHolder deferredResultHolder;
	
	/**
	 * 异步请求controller
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/order")
	//public Callable<String> order() throws Exception{
	// DeferredResult只有等有值了才会返回
	public DeferredResult<String> order() throws Exception{
		logger.info("主线程开始");
		
		// DeferredResult处理异步请求，总共涉及到3个线程
		// 1 main 2 mockQueue 3 QueueListener
		String orderNumber = RandomStringUtils.randomNumeric(8);
		mockQueue.setPlaceOlder(orderNumber);
		
		DeferredResult<String> result = new DeferredResult<>();
		deferredResultHolder.getMap().put(orderNumber, result);
		
		/*Callable<String> result = new Callable<String>(){
			@Override
			public String call() throws Exception {
				logger.info("副线程开始");
				Thread.sleep(1000);
				logger.info("副线程返回");
				return "success";
			}
		};*/
		logger.info("主线程返回");
		return result;
	}
}